const db = require('../tool/db.js');

async function add(data) {

    let [res] = await db.query(`select * from cart where gid=${data.gid} and uid=${data.uid}`)
    if (res.length !== 0) {
        let [res1] = await db.query(`update cart set amount=amount+1 where gid=${data.gid} and uid=${data.uid}`)
        if (res1.affectedRows) {
            return { code: 1, msg: '购物车添加成功', data: '' }
        } else {
            return { code: 0, msg: '添加失败，请重试', data: '' }
        }
    } else {
        let sql = `insert into cart (gid,uid,amount) values (?,?,?)`
        let [result] = await db.query(sql, [data.gid, data.uid, data.amount]);
        if (result.insertId) {
            return { code: 1, msg: '购物车添加成功', data: result.insertId }
        } else {
            return { code: 0, msg: '添加失败，请重试', data: '' }
        }
    }

}

async function list(uid) {
    let sql = `SELECT cart.*,goods.name,goods.price,goods.photo FROM cart LEFT join goods on cart.gid=goods.id WHERE uid=${uid} `
    let [lists] = await db.query(sql);
    // 查询符合条件的总数量
    let [[{ total }]] = await db.query(`SELECT COUNT(*) as total FROM cart LEFT join goods on cart.gid=goods.id WHERE uid=${uid} `)

    return { lists, total }
}

async function mod(data) {
    let sql = `update cart set amount=${data.amount} where id=${data.id}`
    let [res] = await db.query(sql)
    if (res.affectedRows) {
        return { code: 1, msg: '修改成功', data: '' }
    } else {
        return { code: 0, msg: '修改失败', data: '' }
    }
}

async function del(ids) {
    if (typeof ids == 'object') {
        let result = []
        for (const id of ids) {
            console.log(id);
            let sql = `delete from cart where id=${id}`
            let [res] = await db.query(sql)
            if (res.affectedRows) {
                result.push(res.affectedRows)
            }
        }
        if (result.length) {
            return { code: 1, msg: '批量删除成功', data: '' }
        } else {
            return { code: 0, msg: '批量删除失败', data: '' }
        }
    } else {
        let sql = `delete from cart where id=${ids}`
        let [res] = await db.query(sql)
        if (res.affectedRows) {
            return { code: 1, msg: '删除成功', data: '' }
        } else {
            return { code: 0, msg: '删除失败', data: '' }
        }
    }


}

module.exports = { add, list, mod, del }